﻿using MES.Core.Model;
using SqlSugar;

namespace MES.Core.Filter
{
    /// <summary>
    /// 获取自定义http头
    /// </summary>
    public class DataBaseService : IDataBaseService
    {
        protected IHttpHeaderAccessor _httpHeaderAccessor { get; }



        /// <summary>
        /// ctor
        /// </summary>
        /// <param name="httpHeaderAccessor"></param>
        public DataBaseService(IHttpHeaderAccessor httpHeaderAccessor)
        {
            _httpHeaderAccessor = httpHeaderAccessor;
        }

        public SqlSugarClient sqlSugarClient
        {
            get
            {
                var databaseName = _httpHeaderAccessor.HttpHeader["databaseName"];
                SqlSugarHelper sqlSugarHelper = new SqlSugarHelper();
                var res = sqlSugarHelper.Db.Queryable<ConnectionPool>().Where(x => x.IsEnabled == 1).Where(x => x.DatabaseName == databaseName).FirstAsync().GetAwaiter().GetResult();
                if (res == null)
                {
                    throw new Exception("数据库连接不存在");
                }
                sqlSugarHelper.ChangeDB(res.ConnectionString, res.DbType);
                return sqlSugarHelper.Db;
            }
        }
    }
}
